const {app, BrowserWindow, Notification, ipcMain} = require('electron');

let win; //你的窗口需要挂在一个全局变量上, 不然可能会被垃圾回收掉
app.setAppUserModelId(process.execPath)
app.on('ready', () => {
  win = new BrowserWindow({
    width: 300,
    height: 300,
    webPreferences: {
      //默认是使用不到nodejs的能力的,除非你像下面↓这样设置对应的选项
      nodeIntegration: true, // Boolean (optional) - Whether node integration is enabled. Default is false. //主要是安全考虑, 默认是禁用的

      contextIsolation: false //electron12.x 还需要禁用掉此选项 //https://www.electronjs.org/docs/api/context-bridge#contextbridge // https://github.com/electron/electron/issues/28504
      /*
        Like I said I'd rather see the examples you've mentioned updated. But it goes like this:

        1. Use a preload script
        2. Inside the preload script use contextBridge to expose functions to the page https://www.electronjs.org/docs/api/context-bridge#contextbridge
        3. Inside those functions you can use ipcRenderer to communicate with the main process

        In theory you can also disable contextIsolation which was enabled by default with Electron 12. But I do not recommend doing this.
      */
    }
  })

  win.loadFile('./index.html');
  handleIPC()

  // 自动打开调试工具↓
  // win.webContents.openDevTools(); //也可通过快捷键ctrl+shift+i
});

function handleIPC(){
  ipcMain.handle('work-notification', async () => {
    const res = await new Promise((resolve, reject) => {
      const notification = new Notification({
        title: '任务结束了',
        body: '是否开始休息',
        actions: [{text: ' 开始休息', type: 'button'}], //macOS only
        closeButtonText: '继续工作' //macOS only
      });
      notification.show();

      //macOS only
      notification.on('action', () => {
        resolve('rest');
      });


      // Emitted when the notification is closed by manual intervention from the user.
      //
      // This event is not guaranteed to be emitted in all cases where the notification is closed.
      // 自动关闭也会触发该事件
      notification.on('close', () => {
        //会打印在程序运行的控制台 而不是启动的页面的控制台
        console.log('notification closed');
        resolve('work');
      });

      notification.on('click', () => {
        console.log('notification click');
        resolve('rest');
      });
    });

    return res;
  });
}
